/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.system.domain.Courseresources;
import me.zhengjie.modules.system.domain.Courseresourcesmsg;
import me.zhengjie.modules.system.domain.Teacher;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.mapper.TeacherMapper;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.CourseresourcesmsgService;
import me.zhengjie.modules.system.domain.vo.CourseresourcesmsgQueryCriteria;
import me.zhengjie.modules.system.mapper.CourseresourcesmsgMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author shitou
* @date 2024-12-12
**/
@Service
@RequiredArgsConstructor
public class CourseresourcesmsgServiceImpl extends ServiceImpl<CourseresourcesmsgMapper, Courseresourcesmsg> implements CourseresourcesmsgService {

    private final CourseresourcesmsgMapper courseresourcesmsgMapper;

    private final UserMapper userMapper;

    private final TeacherMapper teacherMapper;

    @Override
    public PageResult<Courseresourcesmsg> queryAll(CourseresourcesmsgQueryCriteria criteria, Page<Object> page){

        IPage<Courseresourcesmsg> pageMsg = courseresourcesmsgMapper.findAll(criteria, page);
        List<Courseresourcesmsg> courseresourcesmsgList = pageMsg.getRecords();

        //获取用户id
        List<Integer> createUserIds = new ArrayList<>();
        for(Courseresourcesmsg courseresourcesmsg:courseresourcesmsgList){

            createUserIds.add(Integer.valueOf(courseresourcesmsg.getCreateuserId()));
        }

        List<User> userList = new ArrayList<>();
        if(createUserIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("user_id",createUserIds);
            userList = userMapper.selectList(queryWrapper);
        }
        for(Courseresourcesmsg courseresourcesmsg:courseresourcesmsgList){
            for(User user:userList){

                if(courseresourcesmsg.getCreateuserId()!=null && Integer.valueOf(courseresourcesmsg.getCreateuserId()) == Math.toIntExact(user.getId())){
                    courseresourcesmsg.setCreateUserName(user.getNickName());
                }
            }
        }

        return PageUtil.toPage(pageMsg);
    }

    @Override
    public List<Courseresourcesmsg> queryAll(CourseresourcesmsgQueryCriteria criteria){
        return courseresourcesmsgMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Courseresourcesmsg resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        resources.setSchoolId(Math.toIntExact(currentUser.getDeptId()));
        resources.setCreateuserId(String.valueOf(currentUser.getId()));
        if(teacher!=null){
            resources.setCreateteacherId(String.valueOf(teacher.getId()));
        }

        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Courseresourcesmsg resources) {
        Courseresourcesmsg courseresourcesmsg = getById(resources.getId());
        courseresourcesmsg.copy(resources);
        saveOrUpdate(courseresourcesmsg);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Courseresourcesmsg> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Courseresourcesmsg courseresourcesmsg : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" courseresourcescatalogid",  courseresourcesmsg.getCourseresourcescatalogId());
            map.put(" name",  courseresourcesmsg.getName());
            map.put(" type",  courseresourcesmsg.getType());
            map.put(" createuserid",  courseresourcesmsg.getCreateuserId());
            map.put(" createteacherid",  courseresourcesmsg.getCreateteacherId());
            map.put(" filenmae",  courseresourcesmsg.getFilenmae());
            map.put(" tags",  courseresourcesmsg.getTags());
            map.put(" tagids",  courseresourcesmsg.getTagids());
            map.put(" state",  courseresourcesmsg.getState());
            map.put(" isopen",  courseresourcesmsg.getIsopen());
            map.put(" createtime",  courseresourcesmsg.getCreatetime());
            map.put(" url",  courseresourcesmsg.getUrl());
            map.put(" schoolid",  courseresourcesmsg.getSchoolId());
            map.put(" lastupdatetime",  courseresourcesmsg.getLastupdatetime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}